/**
 * request 请求封装
 */
import baseCfg from './config'

const $api = uni.$u.http

// 设置全局基础配置
$api.setConfig((config) => {
  config = {
    ...config,
    ...baseCfg
  }
  return config
})

// 请求拦截器
$api.interceptors.request.use(
  config => {
    const token = uni.getStorageSync('token')
    if (token && token !== 'undefined') {
      config.header = {
        ...config.header,
        Authorization: 'Bearer ' + token
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
$api.interceptors.response.use(
  res => {
    if (res.data.code === '403') {
      uni.showModal({
        content: '请先注册登录',
        success: res => {
          if (res.confirm) {
            // 清除token
            // store.commit('setToken', '')
            // 跳转登录
            uni.$u.route({
              type: 'redirect',
              url: '/pages/login/login',
              animationType: 'slide-in-right'
            })
          }
        }
      })
    }
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

// 封装请求接口数据
export async function request(config) {
  const cfg = {
    method: config.method ? config.method.toUpperCase() : 'POST',
    ...config
  }
  // console.log('------request------')
  // console.log(cfg)

  try {
    const {
      data
    } = await $api.request(config)
    // 这里根据实际情况，约定返回的code为00时为正确
    if (data.code === '00') {
      return data.data
    } else {
      throw new Error(data.message)
    }
  } catch (e) {
    //TODO handle the exception
    throw new Error(e)
  }
}

uni.$api = $api
